//
//  DGGRouterMediator.m
//  DGGRouter
//
//  Created by Dracy on 2019/7/11.
//  Copyright © 2019 Dracy. All rights reserved.
//

#import "DGGRouterMediator.h"
#import <JLRoutes/JLRoutes.h>
#import <objc/message.h>
#import "DLBaseNavigationController.h"
#import "DLBaseFlutterRootViewController.h"
#import <MJExtension/MJExtension.h>

#define WEAK(weaks,s)  __weak __typeof(&*s)weaks = s;
#define KSB(_SBName_,_name_)  [[UIStoryboard storyboardWithName:[NSString stringWithFormat:@"%@", _SBName_] bundle:nil]instantiateViewControllerWithIdentifier:_name_]

@implementation DGGRouterMediator

+ (instancetype)sharedInstance {
    static DGGRouterMediator *mediator;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mediator = [[DGGRouterMediator alloc] init];
    });
    return mediator;
}

/**
 无参路由注册
 */
- (void)registerModuleNoParameters {
    [[JLRoutes globalRoutes] addRoute:@"/:module/:target/:Bundle/:SBName/:Modal" handler:^BOOL(NSDictionary<NSString *,id> * _Nonnull parameters) {
        return [self goTargetViewController:parameters isParam:NO];
    }];
}

/**
 有参路由注册
 */
- (void)registerModuleParameters {
    [[JLRoutes globalRoutes] addRoute:@"/:module/:target/:Bundle/:SBName/:Modal/:parameter" handler:^BOOL(NSDictionary<NSString *,id> * _Nonnull parameters) {
        return [self goTargetViewController:parameters isParam:YES];
    }];
}


/**
 页面跳转
 
 @param parameters 参数
 @param isParam 是否有参数
 @return Bool
 */
- (BOOL)goTargetViewController:(NSDictionary *)parameters isParam:(BOOL)isParam
{
    NSString *targetClassString = parameters[@"target"];
    NSString *bundleString = parameters[@"Bundle"];
    NSString *SBNameString = parameters[@"SBName"];
    id object;
    if (SBNameString.length > 0) {
        if (bundleString.length > 0) {
            NSString *SBPath = [NSString stringWithFormat:@"%@.bundle/%@", bundleString, SBNameString];
            object = KSB(SBPath, targetClassString);
        } else {
            object = KSB(SBNameString, targetClassString);
        }
    }else {
        Class targetClass = NSClassFromString(targetClassString);
        object = [[targetClass alloc] init];
    }
    // 有参数设置参数
//    if (isParam) {
//        NSDictionary *dic = [parameters[@"parameter"] mj_JSONObject];
//        [object mj_setKeyValues:dic];
//    }
    if (isParam) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[parameters[@"parameter"] mj_JSONObject]];
        if (dict.allKeys.count == 0) return NO;
        for (int i = 0; i < dict.allValues.count ; i++) {
            if ([dict.allValues[i] isKindOfClass:NSString.class] && [dict.allValues[i] containsString:@"^"]) {
                NSString *str = dict.allValues[i];
                [dict setObject:[str stringByReplacingOccurrencesOfString:@"^" withString:@"/"] forKey:dict.allKeys[i]];
            }
        }
        [object mj_setKeyValues:dict];
    }
    
    NSString *modal = parameters[@"Modal"];
    if ([object isKindOfClass:[UIViewController class]]) {
        // 目标视图控制器
        UIViewController *taegetVC = (UIViewController *)object;
        // 获取当前视图控制器
        UIViewController *currentViewController = [DGGCommonSDKUtils currentViewController];
        // Push
        if ([modal isEqualToString:@"push"]) {
            [currentViewController.navigationController pushViewController:taegetVC animated:YES]; 
            return YES;
        }
        else if ([modal isEqualToString:@"present"]) {
            // present
            DLBaseFlutterRootViewController *vc = [DLBaseFlutterRootViewController new];
            DLBaseNavigationController *nav = [[DLBaseNavigationController alloc] initWithRootViewController:vc];
            WEAK(weakNav, nav)
            [currentViewController presentViewController:nav animated:NO completion:^{
                [weakNav pushViewController:taegetVC animated:NO];
            }];
            return YES;
        } else {
            return NO;
        }
    } else {
        return NO;
    }
}

- (void)openModuleWithURLStr:(NSString  *)urlStr
{
    if ([urlStr containsString:@"{"] && [urlStr hasSuffix:@"}"]) {
        [self registerModuleParameters];
        NSString *temp;
        NSInteger loc = 0;
        for(int i =0; i < urlStr.length; i++){
            temp = [urlStr substringWithRange:NSMakeRange(i,1)];
            if ([temp isEqualToString:@"{"]) {
                loc = i;
                break;
            }
        }
        NSString *url;
        if (loc > 0) {
            NSString *routerUrl = [urlStr substringWithRange:NSMakeRange(0, loc)];
            NSString *paramsUrl = [urlStr substringWithRange:NSMakeRange(loc, urlStr.length - loc)];
            paramsUrl = [paramsUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLUserAllowedCharacterSet]];
            
            url = [NSString stringWithFormat:@"%@%@",routerUrl,paramsUrl];
        }else{
            url = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        }
        [self openUrl:[NSURL URLWithString:url]];
    } else {
        [self registerModuleNoParameters];
        [self openUrl:[NSURL URLWithString:[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]]];
    }
}

- (void)openUrl:(NSURL *)url
{
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:url];
        }
    } else {
        [[JLRoutes globalRoutes] routeURL:url];
    }
}

@end
